package com.jlkf.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlkf.common.Constant;
import com.jlkf.dao.DriverAccessoryMapper;
import com.jlkf.pojo.DriverAccessory;
import com.jlkf.service.DriverAccessoryService;
import com.platform.server.response.response.pojo.ReturnData;
import com.platform.server.util.RegexUtil;
import com.platform.server.util.StringTools;
import com.platform.server.util.UUIDUtil;

import Decoder.BASE64Decoder;

@Service
public class DriverAccessoryServiceImpl implements DriverAccessoryService{

	@Autowired
	private DriverAccessoryMapper driverAccessoryMapper;
	
	//车辆列表
	@Override
	public Object getCarList( String startTime, Integer serverType, String endTime,String licensePlate,String models,
			 String vehicleRand, Integer pageNo, Integer pageSize,String order) {
		Map<String,Object> map = new HashMap<>();
		if(!StringTools.isEmpty(startTime)&&!StringTools.isEmpty(endTime)){
			String[] startTime1= startTime.split("/");
	    	String[] endTime1= endTime.split("/");
	    	map.put("startTime", startTime1[2]+"-"+startTime1[1]+"-"+startTime1[0]);
	    	map.put("endTime", endTime1[2]+"-"+endTime1[1]+"-"+endTime1[0]);
		}
		if(!StringTools.isEmpty(models)){
			map.put("models", models);
		}
		if(!RegexUtil.isNull(serverType)){
			map.put("serverType", serverType);
		}
		if(!StringTools.isEmpty(vehicleRand)){
			map.put("vehicleRand", vehicleRand);
		}
		if(!StringTools.isEmpty(licensePlate)){
			map.put("licensePlate", licensePlate);
		}
		if(!StringTools.isEmpty(order)){
			map.put("order", order);
		}
		try {
			PageHelper.startPage(pageNo, pageSize);
			List<DriverAccessory> list = driverAccessoryMapper.getOADriverCar(map);
			PageInfo<DriverAccessory> info = new PageInfo<>(list);
			return new ReturnData(list,(int)info.getPages(),(int)info.getTotal(),200,"success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}
	 //将base64图片 写入文件
		public String getFileUrl(String file,HttpServletRequest request){
			 String  dir= "FAB";     
			 String acesP ="";
			  String path = "";
			if(!"".equals(file)&&file!=null){
				 String content = file.split(";base64,")[1];
				 String jp = file.split(";base64,")[0].split("/")[1];
					// 写入磁盘
					BASE64Decoder decoder = new BASE64Decoder();
					try {
						byte[] decodedBytes = decoder.decodeBuffer(content);
						String trueFileName= UUIDUtil.getOrderSnByTime18()+"."+jp;
						 acesP = "http://"+ Constant.SERVER_NAME+":"+request.getServerPort()+"//"+"file"+"//"+dir+"//"+trueFileName;  
						 // 项目在容器中实际发布运行的根路径
				            String realPath =  request.getSession().getServletContext().getRealPath("/");
				            String path2 = realPath.substring(0,realPath.lastIndexOf(System.getProperty("file.separator")));
				            String p = realPath.substring(0, (path2.lastIndexOf(System.getProperty("file.separator"))))+System.getProperty("file.separator")+"file"+System.getProperty("file.separator")+dir;
				            // 设置存放图片文件的路径
				            path=p+System.getProperty("file.separator")+trueFileName;  
				            File localFile = new File(p+System.getProperty("file.separator"));
				            if(!localFile.exists()){
	                            localFile.mkdirs();
	                        }
						 FileOutputStream out = new FileOutputStream(path);
						out.write(decodedBytes);
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
			}
			return acesP;
		}
	@Override
	public Object addOrUpdate(String json, HttpServletRequest request) {
		DriverAccessory da=	StringTools.json2Obj(json, DriverAccessory.class);
		da.setPicture(getFileUrl(da.getPicture(),request));//车
		da.setNoCriminal(getFileUrl(da.getNoCriminal(),request));//无犯罪
		da.setUpTime(new Date());
		da.setRegistTime(new Date());
		try {
			if(da.getServerType()==1){
				da.setOpenServerType("1");
			}else if(da.getServerType()==2){
				da.setOpenServerType("1,2");
			}else if(da.getServerType()==4){
				da.setOpenServerType("4");
			}else{
				da.setOpenServerType("1,2,3");
			}
			Map<String,Object> map = new HashMap<>();
			map.put("uId", da.getuId());
			List<DriverAccessory> list=driverAccessoryMapper.getCar(map);//查询该司机是否有车
			for(DriverAccessory d:list){//将该司机的所有的车 设为非默认车
				d.setIsDefault(2);
				driverAccessoryMapper.updateByPrimaryKeySelective(d);
			}
			int num=driverAccessoryMapper.insertSelective(da);
			if(num==0){
				return new ReturnData(201,"fail");
			}
			return new ReturnData(200,"success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}
	
	
	@Override
	public Object deleteCar(Long carId) {
		try {
			int num=driverAccessoryMapper.deleteByPrimaryKey(carId);
			if(num==0){
				return new ReturnData(201,"fail");
			}
			return new ReturnData(200,"success");
		} catch (Exception e) {
			e.printStackTrace();
			return new ReturnData(500,"Wow, that's wrong");
		}
	}

}
